<template>
  <div class="breadcrumb">
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 默认样式紧挨着，这里的el-breadcrumb设置在全局样式文件 global.css中 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主体区域 -->
    <el-card class="box-card">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      ></el-alert>
      <el-row class="mianbaoxie">
        <el-col
          >选择商品分类：
          <!-- option指定数据源 -->
          <!-- prop指定配置对象 -->
          <!-- clearable：增加清除功能 -->
          <!-- v-model 存储的值是所有标签对应ID的集合，从一级开始一直到最后一级 -->
          <el-cascader
            clearable
            v-model="cateIds"
            :options="cateList"
            :props="props"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <template>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button
              type="primary"
              :disabled="isSelected()"
              style="margin-bottom: 10px"
              @click="getAddDialog()"
              >添加参数</el-button
            >
            <el-table :data="manyParamList" border stripe>
              <!-- border：显示边框   stripe：隔行变色 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 遍历已有的tab属性部分 -->
                  <el-row>
                    <el-col>
                      <el-tag
                        v-for="(item, i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="tagClose(i,scope.row)"
                        >{{ item }}</el-tag
                      >
                    </el-col>
                  </el-row>
                  <!-- 添加新tab部分 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" lable="#"></el-table-column>
              <el-table-column prop="attr_name" label="属性名称">
              </el-table-column>
              <el-table-column label="操作">
                <!-- size设置按钮大小 -->
                <!-- 通过 template来定义scope，通过其可以获取 row当前行信息，然后.mg_state就是用户状态的参数，设置到 switch 上就能显示状态了 -->
                <template slot-scope="scope">
                  <el-button
                    class="el-icon-edit-outline"
                    type="primary"
                    size="mini"
                    @click="showEditDialog(scope.row.attr_id)"
                  ></el-button>
                  <el-button
                    class="el-icon-delete-solid"
                    type="danger"
                    size="mini"
                    @click="deleteParam(scope.row.attr_id)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button
              type="primary"
              :disabled="isSelected()"
              style="margin-bottom: 10px"
              @click="getAddDialog()"
              >添加属性</el-button
            >
            <el-table :data="onlyParamList" border stripe>
              <!-- border：显示边框   stripe：隔行变色 -->
              <el-table-column type="expand">
                <!-- 遍历已有的tab属性部分 -->
                <template slot-scope="scope">
                  <el-row>
                    <el-col>
                      <el-tag
                        v-for="(item, i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="tagClose(i,scope.row)"
                        >{{ item }}</el-tag
                      >
                    </el-col>
                  </el-row>
                  <!-- 添加新tab部分 -->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput"
                    >+ New Tag</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column type="index" lable="#"></el-table-column>
              <el-table-column prop="attr_name" label="属性名称">
              </el-table-column>
              <el-table-column label="操作">
                <!-- size设置按钮大小 -->
                <!-- 通过 template来定义scope，通过其可以获取 row当前行信息，然后.mg_state就是用户状态的参数，设置到 switch 上就能显示状态了 -->
                <template slot-scope="scope">
                  <el-button
                    class="el-icon-edit-outline"
                    type="primary"
                    size="mini"
                    @click="showEditDialog(scope.row.attr_id)"
                  ></el-button>
                  <el-button
                    class="el-icon-delete-solid"
                    type="danger"
                    size="mini"
                    @click="deleteParam(scope.row.attr_id)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>

      <!-- 添加参数对话框 -->
      <el-dialog
        :title="'添加' + title"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClose"
      >
        <el-form
          :model="addUserForm"
          :rules="paramRules"
          ref="addUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
          ><!-- el-form 的 :model属性值必须对应下面各个分标签的值 -->
          <el-form-item :label="title" prop="attr_name">
            <el-input v-model="addUserForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="commitAddDialog()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改参数对话框 -->
      <el-dialog
        :title="'修改' + title"
        :visible.sync="editDialogVisible"
        width="40%"
        @close="editDialogClose"
      >
        <el-form
          :model="editUserForm"
          :rules="paramRules"
          ref="editUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
          ><!-- el-form 的 :model属性值必须对应下面各个分标签的值 -->
          <el-form-item :label="title" prop="attr_name">
            <el-input v-model="editUserForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="commitEditDialog()"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有的分类数组
      cateList: [],
      // 级联选择器确定的ID数组
      cateIds: [],
      // 级联选择器的配置参数
      props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        // 鼠标放上去就展开，默认需要鼠标点击
        expandTrigger: "hover",
      },
      // el-tabs 默认选择的标签
      activeName: "many",
      // 选中的三级分类ID
      thirdCateId: "",
      // 查询的动态参数数据
      manyParamList: [],
      // 查询的静态属性数据
      onlyParamList: [],
      // 动态标题
      title: "",
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加框中输入的参数名
      addUserForm: {
        attr_name: "",
      },
      editUserForm: {},
      paramRules: {
        attr_name: [
          { required: true, message: "请输入参数名", trigger: "blur" },
          {
            min: 0,
            max: 7,
            message: "参数不能超过 7 个字符",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有的分类
    async getCateList() {
      const { data: res } = await this.$http.get(`categories`);
      if (res.meta.status != 200) {
        this.$http.message.error("分类获取失败!");
      }
      this.cateList = res.data;
    },
    // 级联选择器修改时触发
    handleChange() {
      // 如果不是三级菜单就清空
      if (this.cateIds.length !== 3) {
        this.cateIds = [];
        this.manyParamList = [];
        this.onlyParamList = [];
        return;
      }
      this.getParamList();
    },
    // 判断是否选择第三级分类，来返回是否禁用true或false
    isSelected() {
      if (this.cateIds.length !== 3) {
        return true;
      }
      return false;
    },
    // el-tabs 标签点击事件
    handleClick() {
      this.getParamList();
    },
    // 查询参数值事件
    async getParamList() {
      if (this.cateIds.length != 3) {
        return null;
      }
      this.thirdCateId = this.cateIds[this.cateIds.length - 1];
      const { data: res } = await this.$http.get(
        `categories/${this.thirdCateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status != 200) {
        this.$message.error("查询参数失败！");
      }
      // 这里返回的参数值数组是以字符串返回的，并用空格隔开，所以这里需要先转成数组
      res.data.forEach((item) => {
        // 如果参数值为空，就直接返回一个空数组，如果不照样判断返回的就是一个有一个空字符串元素的数组
        item.attr_vals = item.attr_vals !== "" ? item.attr_vals.split(" ") : [];
        // 为每个对象添加新标签可见参数和新标签属性值参数
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyParamList = res.data;
      } else if (this.activeName === "only") {
        this.onlyParamList = res.data;
      }
    },

    // 点击添加参数按钮触发
    getAddDialog() {
      if (this.activeName === "many") {
        this.title = "动态参数";
      } else {
        this.title = "静态属性";
      }
      this.addDialogVisible = true;
    },
    // 关闭添加参数dialog对话框
    addDialogClose() {
      this.$refs.addUserFormRef.resetFields();
    },
    // 关闭修改参数dialog对话框
    editDialogClose() {
      this.$refs.editUserFormRef.resetFields();
    },
    // 提交添加参数dialog对话框
    async commitAddDialog() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.thirdCateId}/attributes`,
          {
            attr_name: this.addUserForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status != 201) {
          this.$message.error("参数添加失败！");
        }
        this.$message.success("参数添加成功！");
        this.getParamList();
        this.addDialogVisible = false;
      });
    },
    // 显示编辑菜单
    async showEditDialog(attrId) {
      if (this.activeName === "many") {
        this.title = "动态参数";
      } else {
        this.title = "静态属性";
      }

      const {
        data: res,
      } = await this.$http.get(
        `categories/${this.thirdCateId}/attributes/${attrId}`,
        { param: { attr_sel: this.activeName } }
      );
      if (res.meta.status != 200) {
        this.$message.error("参数查询失败！");
      }
      this.editUserForm = res.data;
      this.editDialogVisible = true;
    },
    // 提交修改
    async commitEditDialog() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.thirdCateId}/attributes/${this.editUserForm.attr_id}`,
          this.editUserForm
        );
        if (res.meta.status != 200) {
          this.$message.error("参数更新失败！");
        }
        this.$message.success("参数更新成功！");
        this.getParamList();
        this.editDialogVisible = false;
      });
    },
    // 删除
    async deleteParam(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将删除参数，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); /* 如果有异常就抛出 */
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.thirdCateId}/attributes/${attr_id}`
      );
      if (res.meta.status != 200) {
        this.$message.error("参数值删除失败！");
      }
      this.$message.success("参数值删除成功！");
      this.getParamList();
    },
    // 新标签回车或移除触发事件
    async handleInputConfirm(scopeRow) {
      // 如果没有实际内容就清空
      if(scopeRow.inputValue.trim().length===0){
        scopeRow.inputVisible = false;
        scopeRow.inputValue = '';
        return ;
      }else{
        // 如果输入的有实际内容就添加
        scopeRow.attr_vals.push(scopeRow.inputValue.trim());
        scopeRow.inputValue = '';
        scopeRow.inputVisible = false;
        this.changeParam(scopeRow);
      }
    },
    // 参数项 tab 标签关闭方法
    async tagClose(i,scopeRow){
      // 删除
      scopeRow.attr_vals.splice(i,1);
      this.changeParam(scopeRow);
    },
    // 修改参数项方法
    async changeParam(scopeRow){
       const { data: res } = await this.$http.put(
        `categories/${this.thirdCateId}/attributes/${scopeRow.attr_id}`
      ,{
        attr_name:scopeRow.attr_name,
        attr_sel: scopeRow.attr_sel,
        attr_vals: scopeRow.attr_vals.join(" ")
      });
      if (res.meta.status != 200) {
        this.$message.error("参数项修改失败！");
      }
      this.$message.success("参数项修改成功！");
      // this.getParamList();   使用重新查找数据会使拓展框关闭
      scopeRow = res.data;
    },
    // 点击增加新标签
    showInput(scopeRow) {
      scopeRow.inputVisible = true;
      // 让文本框自动获得焦点
      // $nextTick() 作用：当页面上元素被重新渲染后，才会指行回调函数中代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },
};
</script>

<style scoped lang="less">
.mianbaoxie {
  margin-top: 10px;
}
.el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  margin-top: 5px;
  padding-top: 2px;
  padding-bottom: 0;
}
.input-new-tag {
  margin-top: 5px;
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
